//
//  MessageNotificationViewController.m
//  StormWatch
//
//  Created by Hero on 2024/9/18.
//

#import "MessageNotificationViewController.h"
#import "NotificationManagerCell.h"
#import "MessageNotificationCell.h"

@interface MessageNotificationViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong) UITableView * tableView;
@property (nonatomic, strong) NSMutableArray * dataArr;
/* <#note#> */
@property (nonatomic, assign) BOOL notificationOpen;/* <#note#> */
@property (nonatomic, strong) NSMutableArray * openListArr;
@property (nonatomic, strong) CBPeripheral * peripheral;

@end

@implementation MessageNotificationViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.jy_title = SWString(@"Notification");
    self.openListArr = [[NSMutableArray alloc] init];
    
    
    NSString * uuid = self.metaInfo[@"uuid"];
    NSArray * list = [FRQBluetoothManager shareManager].curPeripherals;
    for (CBPeripheral * per in list) {
        if ([per.identifier.UUIDString isEqualToString:uuid]) {
            self.peripheral = per;
        }
    }
    [self initData];
    [self.view addSubview:self.tableView];
    
    [self readData];
    // Do any additional setup after loading the view from its nib.
}

- (void)readData {
    [[WatchCommandTool sharedInstance] readStormCommand:Command_Notification ToPeripheral:self.peripheral reBack:^(NSString * _Nonnull backData) {
        //  01 0f000000 00
        if (backData.length > 26) {
            NSString * valueStr = [backData substringFromIndex:26];
            self.notificationOpen = ![[valueStr substringToIndex:2] isEqualToString:@"00"];
            
            for (int i = 1; i <= 4; i++) {
                NSString * s1 = [NSString stringWithFormat:@"%lld",strtoll([[NSString stringWithFormat:@"0x%@",[valueStr substringWithRange:NSMakeRange(2 * i, 2)]] UTF8String], 0, 16)];
                NSString *byte1 = [SWTool decimalToBinary:s1];
                
                for (int j = 7; j >= 0; j --) {
                    BOOL b =  [[byte1 substringWithRange:NSMakeRange(j, 1)] isEqualToString:@"1"];
                    [self.openListArr addObject:@(b)];
                }
            }
            
            [self.tableView reloadData];
        }
    }];
}

- (void)initData {
    [self.dataArr addObjectsFromArray:@[SWString(@"Phone"),SWString(@"Messages"),SWString(@"QQ"),SWString(@"WeChat"),SWString(@"Weibo"),SWString(@"Mailbox"),SWString(@"WeChat Work"),SWString(@"Facebook"),SWString(@"WhatsApp"),SWString(@"YouTube"),SWString(@"Skype"),SWString(@"Twitter"),SWString(@"Instagram"),SWString(@"LinkedIn"),SWString(@"NaverCafe"),SWString(@"Between"),SWString(@"KakaoTalk"),SWString(@"Band"),SWString(@"Gmail"),SWString(@"NetFlix"),SWString(@"Telegram"),SWString(@"Line"),SWString(@"163邮箱"),SWString(@"hotmail"),SWString(@"outlook"),SWString(@"snapahat"),SWString(@"TOM"),SWString(@"Yahoo"),SWString(@"Other")]];
}

- (void)initUI {
    self.tableView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight - kNavigationBarHeight - kHomeIndicatorHeight);
    [self.tableView registerNib:[UINib nibWithNibName:@"NotificationManagerCell" bundle:nil] forCellReuseIdentifier:@"NotificationManagerCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"MessageNotificationCell" bundle:nil] forCellReuseIdentifier:@"MessageNotificationCell"];
    [self.view addSubview:self.tableView];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (self.notificationOpen) {
        return 2;
    }
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 1;
    }
    return self.dataArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        NotificationManagerCell * cell = [tableView dequeueReusableCellWithIdentifier:@"NotificationManagerCell" forIndexPath:indexPath];
        cell.swithBtn.on = self.notificationOpen;
        cell.changeBlock = ^(BOOL value) {
            self.notificationOpen = value;
            [self.tableView reloadData];
            [self writeData];
        };
        return cell;
    }else {
        MessageNotificationCell * cell = [tableView dequeueReusableCellWithIdentifier:@"MessageNotificationCell" forIndexPath:indexPath];
        cell.nameLab.text = self.dataArr[indexPath.row];
        cell.swithBtn.on = [self.openListArr[indexPath.row] boolValue];
        cell.changeBlock = ^(BOOL value) {
            [self.openListArr replaceObjectAtIndex:indexPath.row withObject:@(value)];
            [self.tableView reloadData];
            [self writeData];
        };
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return UITableViewAutomaticDimension;
    }
    return 70;
}

- (void)writeData {
    NSMutableArray * copyData = [[NSMutableArray alloc] initWithArray:self.openListArr];
    /// 交换数据位置
    for (int i = 0; i < 4; i ++) {
        [copyData exchangeObjectAtIndex:i withObjectAtIndex:7 - i];
        [copyData exchangeObjectAtIndex:i + 8 withObjectAtIndex:8 + 7 - i];
        [copyData exchangeObjectAtIndex:i + 16 withObjectAtIndex:16 + 7 - i];
        [copyData exchangeObjectAtIndex:i + 24 withObjectAtIndex:24 + 7 - i];
    }
        
    NSString * str = [copyData componentsJoinedByString:@""];
    long byte1 = strtol([[str substringWithRange:NSMakeRange(0, 8)] UTF8String], NULL, 2);
    long byte2 = strtol([[str substringWithRange:NSMakeRange(8, 8)] UTF8String], NULL, 2);
    long byte3 = strtol([[str substringWithRange:NSMakeRange(16, 8)] UTF8String], NULL, 2);
    long byte4 = strtol([[str substringWithRange:NSMakeRange(24, 8)] UTF8String], NULL, 2);

    NSArray * dataArr = @[@(self.notificationOpen),@(byte1),@(byte2),@(byte3),@(byte4)];
    
    [WatchCommandTool.sharedInstance writeStormCommand:Command_Notification ToPeripheral:self.peripheral Value:dataArr reBack:^(NSString * _Nonnull backData) {
        if (backData.length > 26) {
            
        }
    }];
 
}
- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, self.jy_bar_h, kScreenWidth, kScreenHeight - kNavigationBarHeight - kHomeIndicatorHeight) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;

//        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.tableFooterView = [UIView new];
        [_tableView registerNib:[UINib nibWithNibName:@"NotificationManagerCell" bundle:nil] forCellReuseIdentifier:@"NotificationManagerCell"];
        [_tableView registerNib:[UINib nibWithNibName:@"MessageNotificationCell" bundle:nil] forCellReuseIdentifier:@"MessageNotificationCell"];
        if (@available(iOS 11.0, *)) {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
            _tableView.estimatedSectionFooterHeight = 0;
            _tableView.estimatedSectionHeaderHeight = 0;
            _tableView.estimatedRowHeight = 40;
        } else {
            // Fallback on earlier versions
            self.automaticallyAdjustsScrollViewInsets = NO;
        }
        _tableView.scrollsToTop =  NO;
        
        if (@available(iOS 15, *)) {
            _tableView.sectionHeaderTopPadding = 0;
        }
        
    }
    return _tableView;
}


- (NSMutableArray *)dataArr{
    if (!_dataArr) {
        _dataArr = [[NSMutableArray alloc] init];
    }
    return _dataArr;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
